﻿using System;
using System.Collections.Generic;
using System.Text;

namespace MultiViewer
{
    /// <summary>
    /// All calculations that helps user determine what tile to take and where it is from
    /// 
    /// 
    /// 
    /// </summary>
    static public class VirtualEarthCalcs
    {
        private static double earthRadius = 6378137;
        private static double earthCircum = earthRadius * 2.0 * Math.PI;
        private static double earthHalfCirc = earthCircum / 2;



        public static string GetUrl(string quadKey, string mode )
        {
            string mapType = mode; // or "a" for Aerial
            string mapExtension = ".png";

            //TODO what is the ?g= hanging off the end 1 or 15?
            // -- comment above was left by the article author. funny enough to keep it
            string url = String.Concat( new object [] { "http://", mapType, quadKey [quadKey.Length - 1], ".ortho.tiles.virtualearth.net/tiles/", mapType, quadKey, mapExtension, "?g=", 1 } );
            return url;
        }

        public static int LatitudeToYAtZoom( double lat, int zoom )
        {
            double arc = earthCircum / ( ( 1 << zoom ) * 256 );
            double sinLat = Math.Sin( DegToRad( lat ) );
            double metersY = earthRadius / 2 * Math.Log( ( 1 + sinLat ) / ( 1 - sinLat ) );
            int y = ( int )Math.Round( ( earthHalfCirc - metersY ) / arc );
            return y;
        }

        public static int LongitudeToXAtZoom( double lon, int zoom )
        {
            double arc = earthCircum / ( ( 1 << zoom ) * 256 );
            double metersX = earthRadius * DegToRad( lon );
            int x = ( int )Math.Round( ( earthHalfCirc + metersX ) / arc );
            return x;
        }

        public static double DegToRad( double d )
        {
            return d * Math.PI / 180.0;
        }

        public static double MetersPerPixel( int zoom )
        {
            double arc = earthCircum / ( ( 1 << zoom ) * 256 );
            return arc;
        }

        public static string TileToQuadKey( int tx, int ty, int zl )
        {
            string quad = "";
            for ( int i = zl; i > 0; i-- )
            {
                int mask = 1 << ( i - 1 );
                int cell = 1;
                if ( ( tx & mask ) != 0 )
                {
                    cell++;
                }
                if ( ( ty & mask ) != 0 )
                {
                    cell += 2;
                }
                quad += cell;
            }
            return quad;
        }

        
    }
}
